<template>
    <svg
      :class="svgClass"
      :width="size"
      :height="size"
      aria-hidden="true"
      :style="svgStyle"
    >
      <use :xlink:href="iconName"/>
    </svg>
  </template>

  <script setup lang="ts">
  import { computed } from "vue";

  interface Props {
    name: string
    color?: string
    colorful?: boolean  // 是否为彩色图标
    mr?: number
    size?: number | string
    hoverColor?: string  // 悬停时的颜色
  }

  const props = withDefaults(defineProps<Props>(), {
    color: '',
    colorful: false,
    mr: 0,
    size: 20,
    hoverColor: ''
  })

  const iconName = computed(() => `#icon-${props.name}`);

  const svgClass = computed(() => {
    const classes = ['svg-icon']

    if (props.name) {
      classes.push(`icon-${props.name}`)
    }

    // 如果是彩色图标，添加 colorful 类
    if (props.colorful) {
      classes.push('svg-icon-colorful')
    }

    // 如果设置了悬停颜色，添加 hoverable 类
    if (props.hoverColor) {
      classes.push('svg-icon-hoverable')
    }

    return classes.join(' ')
  });

  const svgStyle = computed(() => {
    const style: Record<string, string> = {}

    // 右边距
    if (props.mr) {
      style.marginRight = `${props.mr}px`
    }

    // 如果指定了颜色且不是彩色图标，设置填充色
    if (props.color && !props.colorful) {
      style.fill = props.color
      style.color = props.color
    }

    // 如果设置了悬停颜色
    if (props.hoverColor) {
      style['--hover-color'] = props.hoverColor
    }

    return style
  });
  </script>

  <style lang='scss' scoped>
  .svg-icon {
    fill: currentColor;
    vertical-align: middle;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    display: inline-block;

    // 彩色图标不使用 fill，保留原始颜色
    &.svg-icon-colorful {
      fill: none !important;
      color: inherit !important;

      :deep(path),
      :deep(circle),
      :deep(rect),
      :deep(polygon),
      :deep(ellipse),
      :deep(line),
      :deep(polyline) {
        // 保留 SVG 元素原有的填充色和描边色
        fill: inherit;
        stroke: inherit;
      }
    }

    // 可悬停的图标
    &.svg-icon-hoverable {
      cursor: pointer;

      &:hover {
        fill: var(--hover-color, currentColor);
        color: var(--hover-color, currentColor);
        transform: scale(1.1);
      }
    }

    // 旋转动画
    &.svg-icon-spin {
      animation: svg-spin 1s linear infinite;
    }

    // 脉冲动画
    &.svg-icon-pulse {
      animation: svg-pulse 1.5s ease-in-out infinite;
    }
  }

  @keyframes svg-spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes svg-pulse {
    0%, 100% {
      opacity: 1;
      transform: scale(1);
    }
    50% {
      opacity: 0.5;
      transform: scale(0.9);
    }
  }
  </style>
  
  